from abc import ABC, abstractmethod
from queue import Queue, Full
from threading import Thread
import time
import logging
from ..config import Config
import subprocess
from ..utils.permissions import PermissionManager

logger = logging.getLogger(__name__)

class BaseNotifier(ABC):
    def __init__(self):
        self.config = Config()
        self.queue = Queue(maxsize=20)  # 增加队列容量
        
        # 检查权限
        if not PermissionManager.check_notification_permissions():
            logger.warning("Notification permissions not granted")
        
        self._start_worker()
    
    def _start_worker(self):
        def worker():
            while True:
                try:
                    title, message, timeout = self.queue.get()
                    logger.info(f"正在处理通知: {title}")
                    self._send_notification(title, message, timeout)
                    logger.info(f"通知已发送: {title}")
                    time.sleep(0.5)
                except Exception as e:
                    logger.error(f"处理通知出错: {e}")
                finally:
                    self.queue.task_done()
        
        Thread(target=worker, daemon=True).start()
        logger.info("通知处理线程已启动")
    
    def notify(self, title: str, message: str, timeout: int = None):
        """将通知加入队列"""
        if timeout is None:
            timeout = self.config.NOTIFICATION_TIMEOUT
            
        try:
            self.queue.put_nowait((title, message, timeout))
        except Full:
            logger.warning("通知队列已满，丢弃新通知")
    
    def _handle_error(self, error: Exception):
        """统一的错误处理"""
        error_msg = str(error)
        if isinstance(error, subprocess.CalledProcessError):
            error_msg = error.stderr if error.stderr else error_msg
        logger.error(f"Notification error: {error_msg}")
    
    @abstractmethod
    def _send_notification(self, title: str, message: str, timeout: int = 10):
        """实际发送通知的方法"""
        pass 